package com.zhixinsou.wuyang.process;

import com.alibaba.fastjson.JSON;
import com.zhixinsou.wuyang.model.AnalysisReport;
import com.zhixinsou.wuyang.model.SheetModel;
import com.zhixinsou.wuyang.util.FileUtil;
import com.zhixinsou.wuyang.util.StringUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ProcessFeltl {
    public static List<AnalysisReport> getAnalysisReportPageInfo(String filePath) {
        List<AnalysisReport> reports = new ArrayList<>();
        int startPage = 1;
        File file = new File(filePath);
        String[] lines = FileUtil.pdfReader(file, startPage, startPage).split("\r\n");
        Pattern pattern = Pattern.compile("([0-9]+)\\s-\\s([0-9]+)$");
        while (lines.length > 1 && lines[0].equals("Table of Contents")) {
            for (String line : lines) {
                Matcher matcher = pattern.matcher(line);
                if (matcher.find()) {
                    AnalysisReport report = new AnalysisReport();
                    report.setFilePath(filePath);
                    report.setFileName(file.getName());
                    report.setStartPage(Integer.parseInt(matcher.group(1)));
                    report.setEndPage(Integer.parseInt(matcher.group(2)));
                    report.setBrokerName("Feltl and Company");
                    
                    reports.add(report);
                }
            }

            startPage++;
            lines = FileUtil.pdfReader(filePath, startPage, startPage).split("\r\n");
        }
        return reports;
    }

    public static void getAnalysisReportDetail(AnalysisReport report) {
        Pattern patternVersion = Pattern.compile("Feltl_File\\s([0-9]+)[_]{0,1}");
        Matcher matcher = patternVersion.matcher(report.getFileName());
        if (matcher.find()) {
//            getAnalysisReportDetailVersion(report);
            int version = Integer.parseInt(matcher.group(1));
            if(version == 1)
                getAnalysisReportDetailVersion(report);
            else {
                if(version == 2 && report.getStartPage() < 193)
                    getAnalysisReportDetailVersion(report);
                else
                    getAnalysisReportDetailVersion2(report);
            }
        }
    }
    public static void getAnalysisReportDetailVersion(AnalysisReport report) {
        String content = FileUtil.pdfReader(report.getFilePath(), report.getStartPage(), report.getStartPage(),false);
        String[] lines = content.split("\r\n");

        //Date
        Pattern patternDate = Pattern.compile("(January|February|March|April|May|June|July|August|September|October|November|December){1}\\s*[0-9]+\\S\\s*[0-9]{4}");
        for (int i = 0; i < lines.length; i++) {
            String line = lines[i];
            Matcher matcherDate = patternDate.matcher(line);
            if (matcherDate.find()) {
                report.setDate(matcherDate.group());
                break;
            }
        }

        //Analyst name
        Pattern patternEmail = Pattern.compile("@[a-zA-Z0-9-]+\\.");
        for (int i = 0; i < lines.length; i++) {
            String line = lines[i].trim();
            if(StringUtil.isEmpty(line))
                continue;
            Matcher matcherEmail = patternEmail.matcher(line);
            if (matcherEmail.find()) {
                report.addAnalystName(lines[i - 1]);
            }
        }

        //Ticker
        Pattern patternTicker = Pattern.compile("(.*)\\s*\\(([A-Z]+)\\s*\\-\\s*(\\$[0-9]+\\.[0-9]+)\\)");
        for (int i = 0; i < lines.length; i++) {
            String line = lines[i];
            Matcher matcherTicker = patternTicker.matcher(line);
            if (matcherTicker.find()) {
                report.setCompanyName(matcherTicker.group(1));
                report.setTicker(matcherTicker.group(2));
                String initiatingCoverage = lines[i + 1];
                report.setInitiatingCoverage(initiatingCoverage);
                String[] strings = initiatingCoverage.split("\\s");
                report.setRating(strings[strings.length - 1]);
                break;
            }
        }

        content = FileUtil.pdfReader(report.getFilePath(), report.getStartPage(), report.getEndPage(),false);
        lines = content.split("\r\n");
        List<String> disclosures = new ArrayList<String>();
        List<String> temp = new ArrayList<String>();
        String disclosure = "";
        for(int i = 0; i < lines.length; i++){
            String line = lines[i].trim();
            if(line.contains("does hold a long")) {
                int j = i + 1, k = i - 1;
                //往上和往下找整句
                while(!lines[k].contains(".") && k >= 0){
                    temp.add(lines[k]);
                    k--;
                }
                if(k >= 0)
                    temp.add(lines[k]);
                for(int m = temp.size() - 1; m >= 0; m--){
                    disclosure += temp.get(m) + " ";
                }
                temp.clear();
                disclosure += line + " ";
                while(!lines[j].contains(".") && j < lines.length){
                    disclosure += lines[j] + " ";
                    j++;
                }
                if(j < lines.length)
                    disclosure += lines[j] + " ";
            }
        }
        Pattern patternSentence = Pattern.compile(".*([A-Z][a-z\\S]+\\s[a-z\\S]+\\s[a-z\\S]+\\s[a-z\\S]+.*)");
        String[] values = disclosure.split("\\.");
        for(String value : values){
            System.out.println(value);
            Matcher matcherSentence = patternSentence.matcher(value);
            if(matcherSentence.find() && value.contains("does hold a long")){
                disclosures.add(value);
                break;
            }
        }

        if(disclosures.size() == 0){
            for(String value : values){
                if(value.contains("does hold a long")){
                    disclosures.add(value);
                    break;
                }
            }
        }

        report.setOwnershipDisclosures(disclosures);

        report.setPriorRecommendation("");
        report.setExchange("");
        System.out.println(JSON.toJSON(report));
    }

    public static void getAnalysisReportDetailVersion2(AnalysisReport report) {
        String content = FileUtil.pdfReader(report.getFilePath(), report.getStartPage(), report.getStartPage(),false);
        String[] lines = content.split("\r\n");

        //Date
        Pattern patternDate = Pattern.compile("(January|February|March|April|May|June|July|August|September|October|November|December){1}\\s*[0-9]+\\S\\s*[0-9]{4}");
        for (int i = 0; i < lines.length; i++) {
            String line = lines[i];
            Matcher matcherDate = patternDate.matcher(line);
            if (matcherDate.find()) {
                report.setDate(matcherDate.group());
                break;
            }
        }

        //Analyst name
        Pattern patternEmail = Pattern.compile("@[a-zA-Z0-9-]+\\.");
        for (int i = 0; i < lines.length; i++) {
            String line = lines[i].trim();
            if(StringUtil.isEmpty(line))
                continue;
            Matcher matcherEmail = patternEmail.matcher(line);
            if (matcherEmail.find()) {
                report.addAnalystName(lines[i - 1]);
                String initiatingCoverage = "";
                int j = i + 1;
                for(; j < lines.length; j++){
                    if(!StringUtil.isEmpty(lines[j].trim()))
                        initiatingCoverage += lines[j];
                    else
                        break;
                }
                report.setInitiatingCoverage(initiatingCoverage);
                while (StringUtil.isEmpty(lines[j].trim())){
                    j++;
                }
                report.setCompanyName(lines[j]);
                break;
            }
        }

        //Ticker
        Pattern patternTicker = Pattern.compile("\\(([A-Z]+)\\s*\\-\\s*(\\$[0-9]+\\.[0-9]+)\\)\\s*([A-Za-z]+)");
        for (int i = 0; i < lines.length; i++) {
            String line = lines[i];
            Matcher matcherTicker = patternTicker.matcher(line);
            if (matcherTicker.find()) {
                report.setTicker(matcherTicker.group(1));
                report.setRating(matcherTicker.group(3));
                break;
            }
        }

        content = FileUtil.pdfReader(report.getFilePath(), report.getStartPage(), report.getEndPage(),false);
        lines = content.split("\r\n");
        List<String> disclosures = new ArrayList<String>();
        List<String> temp = new ArrayList<String>();
        String disclosure = "";
        for(int i = 0; i < lines.length; i++){
            String line = lines[i].trim();
            if(line.contains("does hold a long")) {
                int j = i + 1, k = i - 1;
                //往上和往下找整句
                while(!lines[k].contains(".") && k >= 0){
                    temp.add(lines[k]);
                    k--;
                }
                if(k >= 0)
                    temp.add(lines[k]);
                for(int m = temp.size() - 1; m >= 0; m--){
                    disclosure += temp.get(m) + " ";
                }
                temp.clear();
                disclosure += line + " ";
                while(!lines[j].contains(".") && j < lines.length){
                    disclosure += lines[j] + " ";
                    j++;
                }
                if(j < lines.length)
                    disclosure += lines[j] + " ";
            }
        }
        Pattern patternSentence = Pattern.compile(".*([A-Z][a-z\\S]+\\s[a-z\\S]+\\s[a-z\\S]+\\s[a-z\\S]+.*)");
        String[] values = disclosure.split("\\.");
        for(String value : values){
            System.out.println(value);
            Matcher matcherSentence = patternSentence.matcher(value);
            if(matcherSentence.find() && value.contains("does hold a long")){
                disclosures.add(value);
                break;
            }
        }

        if(disclosures.size() == 0){
            for(String value : values){
                if(value.contains("does hold a long")){
                    disclosures.add(value);
                    break;
                }
            }
        }
        report.setOwnershipDisclosures(disclosures);

        report.setPriorRecommendation("");
        report.setExchange("");
        System.out.println(JSON.toJSON(report));
    }

    public static void process(String rootDir, String resultPath) {
        List<AnalysisReport> reports = new ArrayList<>();
        File[] Files = new File(rootDir).listFiles();
        for (File file : Files) {
            if(file.getName().endsWith(".pdf"))
                reports.addAll(getAnalysisReportPageInfo(file.getPath()));
        }

        //以下代码为写入excel
        List<String> headers = new ArrayList<>();
        headers.add("Date");
        headers.add("Broker name");
        headers.add("Analyst name");
        headers.add("Company name");
        headers.add("Ticker");
        headers.add("Exchange");
        headers.add("Rating");
        headers.add("Initiating Coverage");
        headers.add("Prior recommendation");
        headers.add("Ownership disclosure");
        headers.add("PDF file name");
        headers.add("StartPage");
        headers.add("EndPage");
        SheetModel sheetModel = FileUtil.makeSheet(resultPath, "result", headers);

        List<String[]> data = new ArrayList<>();
        for (AnalysisReport report : reports) {
            try {
                getAnalysisReportDetail(report);
            } catch (Exception e) {
                System.out.println(JSON.toJSON(report));
                e.printStackTrace();
                continue;
            }

            String[] line = new String[]{report.getDate(),
                    report.getBrokerName(),
                    JSON.toJSONString(report.getAnalystNames()),
                    report.getCompanyName(),
                    report.getTicker(),
                    report.getExchange(),
                    report.getRating(),
                    report.getInitiatingCoverage(),
                    report.getPriorRecommendation(),
                    JSON.toJSONString(report.getOwnershipDisclosures()),
                    report.getFileName(),
                    report.getStartPage() + "",
                    report.getEndPage() + ""};
            data.add(line);
        }

        FileUtil.exportSheet(sheetModel.getSheet(), data);
        FileUtil.closeSheet(sheetModel);
        System.out.println("Success!");
    }
}
